package io.hepu.robotize.config;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.IdleConnectionEvictor;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

/**
 * HttpClient pool - high performance requirements
 */
@Configuration
public class HttpClientConfiguration {
    @Value("${http.maxTotal}")
    private Integer maxTotal;

    @Value("${http.defaultMaxPerRoute}")
    private Integer defaultMaxPerRoute;

    @Value("${http.socketTimeout}")
    private Integer socketTimeout;

    @Value("${http.connectTimeout}")
    private Integer connectTimeout;

    @Value("${http.connectionRequestTimeout}")
    private Integer connectionRequestTimeout;

    @Value("${http.validateAfterInactivity}")
    private Integer validateAfterInactivity;

    /**
     * 实例化连接池管理器: 设置最大连接数, 并发连接数.
     */
    @Bean(name = "httpClientConnectionManager")
    public PoolingHttpClientConnectionManager getHttpClientConnectionManager() {
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", SSLConnectionSocketFactory.getSocketFactory())
                .build();

        PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(registry);
        manager.setMaxTotal(maxTotal);
        manager.setDefaultMaxPerRoute(defaultMaxPerRoute);
        // Validate connections after 1 sec of inactivity
        manager.setValidateAfterInactivity(validateAfterInactivity);
        return manager;
    }

    /**
     * Create and configure the HttpClientBuilder.
     *
     * @param manager The connection pool manager.
     * @return HttpClientBuilder - Builder for CloseableHttpClient instances.
     */
    @Bean(name = "httpClientBuilder")
    public HttpClientBuilder getHttpClientBuilder(@Qualifier("httpClientConnectionManager")
                                                          PoolingHttpClientConnectionManager manager) {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setDefaultRequestConfig(getHttpConfigBuilder().build());
        httpClientBuilder.setConnectionManager(manager);
        return httpClientBuilder;
    }

    /**
     * Create and configure the CloseableHttpClient instance.
     *
     * @param builder Builder for CloseableHttpClient instances.
     * @return CloseableHttpClient - The HttpClient instance.
     */
    @Bean
    public CloseableHttpClient getHttpClient(@Qualifier("httpClientBuilder") HttpClientBuilder builder) {
        return builder.build();
    }

    /**
     * Create and configure the RequestConfig.Builder.
     *
     * @return RequestConfig.Builder - Builder for creating RequestConfig instances.
     */
    @Bean(name = "httpConfigBuilder")
    public RequestConfig.Builder getHttpConfigBuilder() {
        return RequestConfig.custom().setConnectTimeout(connectTimeout)
                .setConnectionRequestTimeout(connectionRequestTimeout)
                .setSocketTimeout(socketTimeout);
    }

    /**
     * Create and configure the RequestConfig instance.
     *
     * @param builder Builder for creating RequestConfig instances.
     * @return RequestConfig - The request configuration.
     */
    @Bean
    public RequestConfig getRequestConfig(@Qualifier("httpConfigBuilder") RequestConfig.Builder builder) {
        return builder.build();
    }

    /**
     * Start a daemon thread to periodically clean up expired and idle connections.
     *
     * @param manager The connection pool manager.
     * @return IdleConnectionEvictor - The connection evictor thread.
     */
    @Bean
    public IdleConnectionEvictor getIdleConnectionEvictor(@Qualifier("httpClientConnectionManager")
                                                                  PoolingHttpClientConnectionManager manager) {
        IdleConnectionEvictor evictor = new IdleConnectionEvictor(manager, 5, TimeUnit.SECONDS);
        evictor.start();
        return evictor;
    }
}
